package com.srd.phone.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.shengrongdai.srd.R;
import com.srd.phone.bean.UpdateVersionInfo;
import com.srd.phone.utils.MD5FileUtils;
import com.srd.phone.utils.StorageUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadService extends Service {

    private static final int NOTIFY_ID = 0;
    private final int ConnectTimeout = 2 * 1000;
    private final int ReadTimeout = 2 * 1000;

    private final int FLAG_ING = 1; //进行中
    private final int FLAG_COMPLETE = 2; //完成

    private boolean download = false; //是否开始下载了，
    private String apkName = "srd.apk";
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;
    private int progress;
    private UpdateVersionInfo info;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FLAG_ING:
                    int rate = msg.arg1;
                    if (rate < 100) {
                        mBuilder.setContentTitle("下载进度..." + rate + "%");
                        mBuilder.setProgress(100, rate, false);
                    } else {
                        mBuilder.setContentTitle("下载完成");
                        mBuilder.setContentText("文件已下载完毕");
                        stopSelf();// 停掉服务自身
                    }
                    mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
                    break;
                case FLAG_COMPLETE:
                    mNotificationManager.cancel(NOTIFY_ID);
                    installApk();
                    break;
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            info = (UpdateVersionInfo) intent.getSerializableExtra("info");
        }
        if (download == false) {
            new Thread(runnable).start();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //下载文件的方法，加上同步，防止多个线程同时操作一个文件，
    private synchronized void downloadFile() {
        HttpURLConnection conn = null;
        InputStream input = null;
        RandomAccessFile raf = null;
        try {
            int contentLength = -1;
            File file = new File(StorageUtils.getFile(DownloadService.this), apkName);
            raf = new RandomAccessFile(file, "rwd");
            URL url = new URL(info.url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(ConnectTimeout);
            conn.setReadTimeout(ReadTimeout);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                contentLength = conn.getContentLength();
            }
            conn.disconnect();
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(ConnectTimeout);
            conn.setReadTimeout(ReadTimeout);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Range", "bytes=" + file.length() + "-" + contentLength); //是个闭合区间
            raf.seek(file.length());//表示指针开始位置
            if (conn.getResponseCode() == 206) { //206表示部分内容，跟range配合这用
                input = conn.getInputStream();
                byte[] buffer = new byte[1024 * 4];
                int len = -1;
                long currentLength = file.length();
                while ((len = input.read(buffer)) != -1) {
                    raf.write(buffer, 0, len);
                    currentLength += len;
                    progress = (int) (((float) currentLength / contentLength) * 100);
                    Message msg = handler.obtainMessage();
                    msg.what = FLAG_ING;
                    msg.arg1 = progress;
                    handler.sendMessage(msg);
                    if (currentLength >= contentLength) {
                        handler.sendEmptyMessage(FLAG_COMPLETE);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
                raf.close();
                conn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            download = true;
            setUpNotification();
            downloadFile();
            download = false;
        }
    };

    /**
     * 创建通知
     */
    private void setUpNotification() {
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setWhen(System.currentTimeMillis()).setTicker("正在下载").setSmallIcon(R.mipmap.ic_launcher).setSmallIcon(R.mipmap.ic_launcher);
        mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
        Notification mNotification = mBuilder.build();
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.download_notification_layout);
        contentView.setTextViewText(R.id.name, "正在下载...");
        // 指定个性化视图
        mNotification.contentView = contentView;
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
        // 指定内容意图
        mNotification.contentIntent = contentIntent;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    /**
     * 安装apk
     *
     * @param url
     */
    private void installApk() {
        try {
            File apkfile = new File(StorageUtils.getFile(DownloadService.this), apkName);
            if (!apkfile.exists()) {
                return;
            }
            String md5 = MD5FileUtils.getFileMD5String(apkfile);
            if (!md5.equalsIgnoreCase(info.md5)) { //md5值校验
                return;
            }
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
            startActivity(i);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
